﻿using System;
using System.Globalization;
using System.Text;
using Amiable.SDK;
using Amiable.SDK.Enum;
using Amiable.SDK.EventArgs;
using Amiable.SDK.Interface;
using AmiCheckin.Code.Util;

// ReSharper disable PossibleNullReferenceException
// ReSharper disable InconsistentNaming

namespace AmiCheckin.Code.BotEvents
{
    public class CheckinCommand : IPluginEvent
    {
        public void Process(AmiableEventArgs _e)
        {
            var e = _e as AmiableMessageEventArgs;

            //根据消息和群号匹配可用签到设置组
            var sets = CheckinEnableUtil.GetSets(e.RawMessage, e.GroupId);

            var sb = new StringBuilder();

            foreach (var tuple in sets)
            {
                var setName = tuple.key;
                var set = tuple.set;
                if (DataUtil.CanCheckin(e.GroupId, e.UserId, setName))
                {
                    //用户对这个组可以签到
                    DataUtil.SetCheckin(e.GroupId, e.UserId, setName);
                    DataUtil.AddCoin(e.GroupId, e.UserId, set, out var dic);
                    //组合replies
                    set.Replies.ForEach(str =>
                    {
                        //得到的coin数据替换
                        dic.ForEach(x =>
                            str = str.Replace($"[reward:{x.Item1}]",
                                Math.Round(x.Item2, 2).ToString(CultureInfo.InvariantCulture)));
                        //替换变量
                        str = str.ReplaceWithQQandGroup(e.UserId, e.GroupId);
                        sb.AppendLine(str);
                    });
                }
                else
                {
                    sb.AppendLine($"{tuple.key}:签到失败");
                }
            }
            if (sb.ToString() != "") e.SendMessage(sb.ToString());
        }

        public AmiableEventType EventType => AmiableEventType.Group;
    }
}